<?php

namespace App\Exceptions;

use App\Models\ApiResult;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        InvalidRequestException::class,
        CouponCodeUnavailableException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function report(Throwable $e)
    {
//        if ($this->shouldReport($e)) {
//        }
//        parent::report($e);
    }

    public function render($request, \Throwable $e)
    {
        $s = sprintf("[%s]%s:%d  %s (%d) [%s]", $request->getRequestUri(), $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
        Log::error($s);
        if (strpos($request->getRequestUri(), "/admin") === 0) { //判断后台
            return parent::render($request, $e);
        }

        if ($e instanceof UnauthorizedException) {
            return response()->json(ApiResult::failure($e->getCode(), __('未授权')));
        }

        if ($e instanceof NotFoundHttpException) {
            return response()->json(ApiResult::failure($e->getCode(), __('接口不存在')));
        }

        if ($e instanceof MethodNotAllowedHttpException) {
            return response()->json(ApiResult::failure($e->getCode(), __('方法不存在')));
        }


        $code = $e->getCode();
        if (!(is_numeric($code))) {
            $code = 405;
        }

        return response()->json(ApiResult::failure($code, "系统异常"));
    }


}
